package com.sharing.service;

import com.sharing.common.Page;
import com.sharing.common.Result;
import com.sharing.domain.*;
import com.sharing.mapper.UserMapper;
import io.netty.handler.timeout.ReadTimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import sun.nio.cs.US_ASCII;

import javax.jws.soap.SOAPBinding;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.TooManyListenersException;

/**
 * @author MingTian
 * @version 1.0
 * @description TODO
 * @date 2023/4/1 22:56
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserHobbyService userHobbyService;

    @Autowired
    private UserProductionService userProductionService;

    /**
     * 根据用户id查询用户基本信息的业务层方法
     * @param id
     * @return
     */
    public Result<User> selectUserById(Integer id) {
        User user = userMapper.selectUserById(id);

        return new Result<>(0, user);
    }

    /**
     * 根据用户名查询用户基本信息的业务层方法
     * @param userName
     * @return
     */
    public Result<User> selectUserByUserName(String userName) {
        User user = userMapper.selectUserByUserName(userName);

        return new Result<>(0, user);
    }

    /**
     * 分页查询用户基本信息的业务层方法
     * @param page
     * @param size
     * @return
     */
    public Result<Page<User>> selectUsersByPage(Integer page, Integer size) {
        List<User> users = userMapper.selectUsersByPage((page - 1) * size, size);

        // 查询总数
        Integer total = userMapper.selectUsersNumByPage();

        Page<User> page1 = new Page<>(total, size, users);

        return new Result<>(0, page1);
    }

    /**
     * 根据用户身份查询用户基本信息的业务层方法
     * @param identity
     * @return
     */
    public Result<Page<User>> selectUsersByIdentity(String identity, Integer page, Integer size) {
        if (identity == null) {
            return new Result<>(1, "identity参数传入不当");
        }
        if (!identity.equals("管理用户") && !identity.equals("普通用户")) {
            return new Result<>(1, "identity参数传入不当");
        }

        List<User> users = userMapper.selectUsersByIdentity(identity, (page - 1) * size, size);

        // 查询总数
        Integer total = userMapper.selectUsersNumByIdentity(identity);

        Page<User> page1 = new Page<>(total, size, users);

        return new Result<>(0, page1);
    }

    /**
     * 根据城市查询用户基本信息的业务层方法
     * @param city
     * @param page
     * @param size
     * @return
     */
    public Result<Page<User>> selectUsersByCity(String city, Integer page, Integer size) {
        if (city == null) {
            return new Result<>(1, "city参数传入不当");
        }

        List<User> users = userMapper.selectUsersByCity(city, (page - 1) * size, size);

        // 查询总数
        Integer total = userMapper.selectUsersNumByCity(city);

        Page<User> page1 = new Page<>(total, size, users);

        return new Result<>(0, page1);
    }

    /**
     * 根据城市、身份、年龄范围进行用户基本信息查询的业务层方法
     * @param citys
     * @param identity
     * @param minAge
     * @param maxAge
     * @param page
     * @param size
     * @return
     */
    public Result<Page<User>> selectUsersByMultCondition(List<String> citys, String identity, Integer minAge, Integer maxAge, Integer page, Integer size) {
        List<User> users = userMapper.selectUsersByMultCondition(citys, identity, minAge, maxAge, (page - 1) * size, size);

        // 查询总数
        Integer total = userMapper.selectUsersNumByMultCondition(citys, identity, minAge, maxAge);

        Page<User> page1 = new Page<>(total, size, users);

        return new Result<>(0, page1);
    }

    /**
     * 新增用户的业务层方法
     * @param user
     * @return
     */
    public Result<User> insertUser(User user) {
        if (user == null) {
            return new Result<>(1, "新增失败——传入用户信息为NULL");
        }
        User user1 = userMapper.selectUserByUserName(user.getUserName());
        if (user1 != null) {
            return new Result<>(1, "该用户名已存在");
        }

        System.out.println(user + "......................................................");
        Integer rows = userMapper.insertUser(user);
        System.out.println(user + "......................................................");

        if (rows == 0) {
            return new Result<>(1, "新增失败");
        }
        user = userMapper.selectUserById(user.getId());
        if (user == null) {
            return new Result<>(1, "新增失败");
        }

        return new Result<>(0, user);
    }

    /**
     * 删除用户的业务层方法
     * @param id
     * @param userName
     * @return
     */
    public Result<Integer> deleteUser(Integer id, String userName) {
        int rows = 0;
        if (id != null) {
            rows = userMapper.deleteUserById(id);
            if (rows != 0) {
                return new Result<>(0, rows);
            }
        }
        if (userName != null) {
            rows = userMapper.deleteUserByUserName(userName);
            if (rows != 0) {
                return new Result<>(0, rows);
            }
        }

        return new Result<>(1, "删除失败");
    }

    /**
     * 修改用户信息的业务层方法
     * @param user
     * @return
     */
    public Result<Integer> updateUser(User user) {
        // 从数据库先查到需要修改的用户信息
        Integer id = user.getId();
        User user1 = userMapper.selectUserById(id);

        if (user1 == null) {
            return new Result<>(1, "该id在数据库中不存在");
        }

        // 合法性校验———校验密码
        try {
            if (DigestUtils.md5DigestAsHex(user.getPassword().getBytes("utf-8")).equals(user1.getPassword())) {
                // 校验成功
                int rows = userMapper.updateUser(user);
                if (rows == 0) {
                    return new Result<>(1, "修改失败");
                }
                return new Result<>(0, rows);
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        return new Result<>(1, "密码不正确");
    }

    /**
     * 通过用户ids查询用户基本信息的业务层方法
     * @param ids
     * @return
     */
    public Result<Page<User>> selectUsersByIds(List<Integer> ids, Integer page, Integer size) {
        Integer total = userMapper.selectUsersNumByIds(ids);
        List<User> users = userMapper.selectUsersByIds(ids, (page - 1) * size, size);

        return new Result<>(0, new Page<>(total, size, users));
    }

    /**
     * 根据该用户的位置查询附近用户
     * @param user
     * @param page
     * @param size
     * @return
     */
    public List<User> selectUserByPosition(User user, Integer page, Integer size) {
        List<User> users = userMapper.selectUserByPosition(user, (page - 1) * size, size);

        return users;
    }

    /**
     * 查询用户的首页信息
     * 包括用户的基本信息（除密码、电话等隐私信息）、
     * 用户自身所勾选的兴趣、
     * 用户置顶作品和最新作品
     * @param id
     * @return
     */
    public Result<UserFirstPage> selectUserFirstPage(Integer id) {
        // 查询用户基本信息
        // 并进一步删除用户的隐私信息
        User user = userMapper.selectUserById(id);
        user.setPassword(null);
        user.setPhone(null);

        // 查询用户的兴趣
        List<Hobby> userHobbies = userHobbyService.selectHobbyByUserId(id, 1, 1, 5).getData().getResult();

        List<Hobby> userHobbies_ = userHobbyService.selectHobbyByUserId(id, 2, 1, 5).getData().getResult();

        userHobbies.addAll(userHobbies_);

        // 查询用户作品
        List<UserProduction> userProductions = userProductionService.selectContentByUserId(id, 1, 20).getData().getResult();

        UserFirstPage userFirstPage = new UserFirstPage(user, userHobbies, userProductions);

        return new Result<>(0, userFirstPage);
    }
}
